import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Anastasia
 * Date: 16.12.14
 * Time: 0:09
 * To change this template use File | Settings | File Templates.
 */
public class Add extends JFrame implements ActionListener
{
    private Employee employee;

  //  private int count=0;
    private Add addwindow;

    private  ArrayList<Department> departments;

     public Add()
     {
         employee = new Employee();

     }


    public class Changer extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                 panel.remove(changer);
                panel.remove(dep);

               // withoutDeparmentbutton = new JButton("Без отдела");
               // withoutDeparmentbutton.setBounds(200,250,200,30);
                panel.add(withoutDeparmentbutton);

               // withoutDeparmentbutton.addActionListener(new WithoutDepartment());     //добавление обработчика на кнопку без отдела


               // existDepartmentbutton = new JButton("Существуюший отдел");
              //  existDepartmentbutton.setBounds(410,250,200,30);
                panel.add(existDepartmentbutton);

              //  existDepartmentbutton.addActionListener(new GetterofDepartment());   //вывод существующих отделов
                panel.validate();
                panel.repaint();

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }


    public class ChooseDepartment extends Thread implements ActionListener     //для обработки нажатия на комбо бокс
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                int index=-1;




            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }
    public class WithoutDepartment extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {

                employee.setDepartment(null);
               panel.remove(withoutDeparmentbutton);
                panel.remove(existDepartmentbutton);
                panel.repaint();

                changer = new JButton("Изменить");
                changer.setBounds(450, 250, 200, 30);

                changer.addActionListener(new Changer());
                panel.add(changer);
                if(employee.getDepartment()==null)
                {
                dep = new JLabel("Сотрудник без отдела");
                }
                else {dep = new JLabel(employee.getDepartment().getName());}

                dep.setBounds(260,250,150,30);
                panel.add(dep);
                panel.repaint();
                panel.validate();


            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }

    public class Selector extends Thread implements ActionListener     //обработчик на выбор сотрудника;
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                int index=-1;
                index = list.getSelectedIndex();

                Department department1 = departments.get(index);
                dep  = new JLabel(department1.getInfo());
                employee.setDepartment(department1);
                changer = new JButton("Изменить");
                changer.setBounds(650, 250, 200, 30);


                changer.addActionListener(new Changer());
                panel.add(changer);
                panel.remove(list);
                dep.setBounds(200, 250, 450, 30);
                panel.add(dep);
                panel.repaint();
                panel.validate();

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }

    public class GetterofDepartment extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
               // JOptionPane.showMessageDialog(null,"Список отделов пуст", "Inane error",
                       // JOptionPane.ERROR_MESSAGE);



                InetAddress addr = InetAddress.getByName(null);
                Socket socket = new Socket(addr, 8080);

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(12,null));
                //  System.out.println("Ok");

                out.flush();  //чудный метод.

                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();

                departments = (ArrayList<Department>)object;



                if(departments == null||departments.size()==0)
                {
                       JOptionPane.showMessageDialog(null,"Список отделов пуст", "Error",
                               JOptionPane.ERROR_MESSAGE);


                }
                else{

                    panel.remove(withoutDeparmentbutton);
                    panel.remove(existDepartmentbutton);
                    panel.repaint();
                    String info[]= new String[departments.size()];

                    for(int i =0;i< departments.size();i++)
                    {
                        info[i]=departments.get(i).getInfo();
                    }
                        list = new JComboBox(info);

                    list.setBounds(300,250,300,50);
                    list.setVisible(true);
                    list.addActionListener(new Selector());
                    panel.add(list);
                    panel.repaint();
                    panel.validate();

                }

            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }



    public class SendEmployee extends Thread implements ActionListener  {


        public void actionPerformed(ActionEvent arg0)
        {

            try {
               // Employee employee = new Employee(name.getText(),surname.getText(), lastname.getText(), pay.getText(), phone.getText());


                employee.setName(name.getText());
                employee.setSurname(surname.getText());
                employee.setLastName(lastname.getText());
                employee.setPay(pay.getText());
                employee.setPhoneNumber(phone.getText());


                InetAddress addr = InetAddress.getByName(null);



                Socket socket = new Socket(addr, 8080);

               // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(1,employee));
              //  System.out.println("Ok");

                out.flush();  //чудный метод.
                //socket.getOutputStream().write(("inputfromclient").getBytes());
                // read answer
             /*   byte buf[] = new byte[64*1024];
                int r = socket.getInputStream().read(buf);
                String data = new String(buf);
                // Out answer to Java console
               // System.out.println(data);
                res.setVisible(true);
                res.setText(data);
                panel.repaint();
                panel.validate();

                                    */

                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();


                String data = (String)object;

                if (data.equals("0"))
                {
                   addwindow.dispose();
                    JOptionPane.showMessageDialog(null,"Сотрудник добавлен", "OK",
                            JOptionPane.INFORMATION_MESSAGE);

                }
                else{
                    if(data.equals("1"))
                    {    JOptionPane.showMessageDialog(null,"Неверное имя сотрудника", "Error",
                            JOptionPane.ERROR_MESSAGE);

                    }
                   if(data.equals("3"))
                   {
                       JOptionPane.showMessageDialog(null,"Неверная фамилия сотрудника", "Error",
                               JOptionPane.ERROR_MESSAGE);
                   }
                    if(data.equals("2"))
                    {
                        JOptionPane.showMessageDialog(null,"Неверное отчество сотрудника", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }

                    if(data.equals("4"))
                    {
                        JOptionPane.showMessageDialog(null,"Неверная зарплата сотрудника", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }
                    if(data.equals("5"))
                    {
                        JOptionPane.showMessageDialog(null,"Неверный телефон сотрудника", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }

                }
                 out.close();
                in.close();
                socket.close();
            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }

          // dispose();  закрыть окно по кнопке

        }
    }

    private JButton button;
    private  JPanel panel = new JPanel();
    private JLabel Label;

    private JComboBox list;
    private JLabel namelabel= new JLabel("Имя");
    private JLabel surnamelabel= new JLabel("Отчество");
    private JLabel lastnamelabel = new JLabel("Фамилия");
    private JLabel departmentlabel = new JLabel("Департамент");
    private JLabel paylabel = new JLabel("Зарплата");
    private JLabel  phonelabel = new JLabel("Телефон");
    private JTextField name = new JTextField(10);
    private JTextField surname;
    private JTextField lastname;
    private JTextField department;
    private JTextField pay;
    private JTextField phone;
    private JButton withoutDeparmentbutton;
    private JButton existDepartmentbutton;
    private JTextField res;
    private JButton  changer;
    private JLabel dep;



   public void setVisionOndepartment(boolean bool)
   {
       withoutDeparmentbutton.setVisible(bool);
   }

    public void actionPerformed(ActionEvent arg0)
    {

    /*  try{

     InetAddress addr = InetAddress.getByName(null);

        Socket socket = new Socket(addr, 8080);

                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter outer = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())), true);
        outer.println(1);  //это будет команда


        socket.close();  }

        catch(UnknownHostException e)
        {

        }

        catch(IOException e)
        {

        }
             */



        addwindow = new Add();             //this
        addwindow.setVisible(true);
        addwindow.setBounds(100,100,1000,1000);
        panel = new JPanel();
        panel.setLayout(null);

        res = new JTextField();
        res.setBounds(100, 30, 400, 30);

        panel.add(res);
        res.setVisible(false);


        namelabel = new JLabel("Имя");
        namelabel.setBounds(100,100,80,30);
        panel.add(namelabel) ;

        name = new JTextField();
        name.setBounds(200, 100, 200, 30);

        panel.add(name);


        surnamelabel = new JLabel("Отчество");
        surnamelabel.setBounds(100,150,80,30);
        panel.add(surnamelabel) ;

        surname = new JTextField();
        surname.setBounds(200, 150, 200, 30);

        panel.add(surname);


        lastnamelabel = new JLabel("Фамилия");
        lastnamelabel.setBounds(100,200,80,30);
        panel.add(lastnamelabel) ;

        lastname = new JTextField();
        lastname.setBounds(200, 200, 200, 30);

        panel.add(lastname);

        departmentlabel = new JLabel("Департамент");
        departmentlabel.setBounds(100,250,80,30);
        panel.add(departmentlabel) ;

        //department = new JTextField();
        //department.setBounds(200, 250, 200, 30);


    //    panel.add(department);


        withoutDeparmentbutton = new JButton("Без отдела");
        withoutDeparmentbutton.setBounds(200,250,200,30);
        panel.add(withoutDeparmentbutton);

        withoutDeparmentbutton.addActionListener(new WithoutDepartment());     //добавление обработчика на кнопку без отдела


        existDepartmentbutton = new JButton("Существуюший отдел");
        existDepartmentbutton.setBounds(410,250,200,30);
        panel.add(existDepartmentbutton);

        existDepartmentbutton.addActionListener(new GetterofDepartment());   //вывод существующих отделов


        paylabel = new JLabel("Зарплата");
        paylabel.setBounds(100,300,80,30);
        panel.add(paylabel) ;

        pay = new JTextField();
        pay.setBounds(200, 300, 200, 30);

        panel.add(pay);

        list = new JComboBox();
        list.setBounds(50,450,200,200);
        panel.add(list);
        list.setVisible(false);

        phonelabel = new JLabel("Телефон");
        phonelabel.setBounds(100,350,80,30);
        panel.add(phonelabel) ;

        panel.validate();


        phone = new JTextField();
        phone.setBounds(200, 350, 200, 30);

        panel.add(phone);

        button = new JButton("ОК");            //завершающая.
        button.setBounds(150,400,200,30);
        panel.add(button);

        button.addActionListener(new SendEmployee());
        panel.validate();



        addwindow.add(panel);
        addwindow.setPreferredSize(new Dimension(500, 800));

        panel.repaint();



    }
}
